4_ProductIngredientSeeder.ts ➔ run   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 23
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 23
c 0
b 0
f 0
rs 9.376
cc 3
1
import BaseSeeder from '@ioc:Adonis/Lucid/Seeder'
2
import Merchant from 'App/Models/Merchant'
3
import Product from 'App/Models/Product'
4
import Ingredient from 'App/Models/Ingredient'
5
6
const PRODUCT_INGREDIENTS = {
7
  beef: 150,
8
  cheese: 30,
9
  onion: 20,
10
}
11
12
export default class extends BaseSeeder {
13
  public async run () {
14
    // Write your database queries inside the run method
15
    const product = await Product.findBy('name', 'Burger')
16
    const merchant = await Merchant.query()
17
          .withScopes((scopes) => scopes.merchant())
18
          .where('email', '[email protected]')
19
          .first()
20
21
    if (!(product && merchant)) {
22
      return
23
    }
24
25
    const ingredients = await Ingredient.all()
26
27
    await Promise.all(ingredients.map(async (ingredient: Ingredient) => {
28
      const productIngredients = await product.related('ingredients').query()
29
              .wherePivot('ingredient_id', ingredient.id).first()
30
31
      if (!productIngredients) {
32
        await product.related('ingredients').attach({
33
          [ingredient.id]: {
34
            quantity: PRODUCT_INGREDIENTS[ingredient.name.toLowerCase()],
35
            user_id: merchant.id
36
          }
37
        })
38
      }
39
    }))
40
  }
41
}
42